'''
Author: LIFM0623 1944099171@qq.com
Date: 2024-03-12 21:54:30
LastEditors: LIFM0623 1944099171@qq.com
LastEditTime: 2024-03-13 14:24:06
FilePath: \scene_back_nest\python\getImagerasterbbox.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''

from osgeo import gdal, osr
import sys

# 获取tif的bbox 边界


def get_bbox(dataset):
    # 获取数据集的投影
    projection = dataset.GetProjection()
    # 检查投影是否为地理坐标系（0/1）
    spatialRef = osr.SpatialReference(projection)
    isGeographic = spatialRef.IsGeographic()
    # 获取外边框信息
    geoTransform = dataset.GetGeoTransform()
    topLeftX = geoTransform[0]
    topLeftY = geoTransform[3]
    pixelWidth = geoTransform[1]
    pixelHeight = geoTransform[5]
    width = dataset.RasterXSize
    height = dataset.RasterYSize
    # 计算左下角经纬度
    bottomLeftX = topLeftX
    bottomLeftY = topLeftY + (height * pixelHeight)
    # 计算右上角经纬度
    topRightX = topLeftX + (width * pixelWidth)
    topRightY = topLeftY
    # 如果投影是地理坐标系，则直接使用地理坐标
    if isGeographic == 1:
        bottomLeft = [bottomLeftX, bottomLeftY]
        topRight = [topRightX, topRightY]
    else:
        # 否则，进行坐标转换
        # 创建地理坐标转换器
        geographicRef = spatialRef.CloneGeogCS()
        transform = osr.CoordinateTransformation(spatialRef, geographicRef)
        # 转换为经纬度坐标
        bottomLeft = transform.TransformPoint(bottomLeftX, bottomLeftY)
        topRight = transform.TransformPoint(topRightX, topRightY)
        # 平面坐标系的（x,y)分别对应地理坐标系的（维度，经度）,所以需要调换一下顺序
        bottomLeft = [bottomLeft[1], bottomLeft[0]]
        topRight = [topRight[1], topRight[0]]

    # 存储结果到List[float]
    bbox = []
    bbox.append(bottomLeft[0])  # 左下经度
    bbox.append(bottomLeft[1])  # 左下纬度
    bbox.append(topRight[0])  # 右上经度
    bbox.append(topRight[1])  # 右上纬度
    bboxString = str(bottomLeft[0]) + ',' + str(bottomLeft[1]) + \
        ',' + str(topRight[0]) + ',' + str(topRight[1])

    return bboxString


if __name__ == "__main__":
    # 获取关键字参数
    file_path = sys.argv[1]
    # file_path = E:/Scene + '/1944099171@qq.com/imageraster/1710250902370.tif'

    dataset = gdal.Open(file_path)

    bbox = get_bbox(dataset)
    print(bbox)
